package com.example.client_anna.module.branch_explore;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.client_anna.R;
import com.example.client_anna.base.BaseActivity;
import com.example.client_anna.util.adapter.CommentAdapter;
import com.example.client_anna.util.entity.Explore_comment;
import com.example.client_anna.network.okhttp3.HttpUtilImpl;
import com.example.client_anna.util.entity.User;
import com.example.client_anna.network.okhttp3.RequestUrl;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
public class ExploreDetailsActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "details_Activity";

    //接收explore界面传递过来的值
    public static final String USER_ID = "userid";
    public static final String EXPLORE_ID = "exploreid" ;
    public static final String EXPLORE_THEME = "exploretheme" ;
    public static final String IMAGES_URL = "imagesurl" ;
    public static final String EXPLORE_STORY = "story";

    private User user;
    private TextView details_textView;
    private TextView details_username;
    private EditText details_edit;
    private ImageView details_images;
    private RecyclerView recyclerView;
    private ImageView imageView;

    private List<Explore_comment> explore_comment = new ArrayList<>();
    Explore_comment addcomment = new Explore_comment();
    private CommentAdapter commentAdapter;

    //登录用户的信息
    private String user_id;
    private String user_name;
    private String user_picture;

    private String explore_userid;
    private String exploreid;
    private String getedit;
    private String backjson;
    @SuppressLint("ResourceType")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_explore_details);

        //获取UI展示界面传递过来的值
        Intent intent = getIntent();
        //用来获取分享该信息的用户信息
        explore_userid = intent.getStringExtra(USER_ID);
        //用来申请服务器上该分享信息的所有评论
        exploreid = intent.getStringExtra(EXPLORE_ID);
        //具体分享内容
        String exploretheme = intent.getStringExtra(EXPLORE_THEME);
        String imagesurl = intent.getStringExtra(IMAGES_URL);
        String story =  intent.getStringExtra(EXPLORE_STORY);

        //Toolbar实例化
        Toolbar toolbar = (Toolbar)findViewById(R.id.details_toolbar);
        //折叠式标题栏CollapsingToolbarLayout实例化
        CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)
                findViewById(R.id.details_collapsing_toolbar);
        //ImageView实例化
        ImageView details_imageView = (ImageView)findViewById(R.id.details_images);
        //TextView实例化
        details_textView = (TextView)findViewById(R.id.details_text);
        details_username = (TextView)findViewById(R.id.details_username);
        //加载toolbar
        setSupportActionBar(toolbar);

        //系统自带导航栏
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            //系统自带的返回按钮
            actionBar.setDisplayHomeAsUpEnabled(true);
            //按钮图片
            actionBar.setHomeAsUpIndicator(R.drawable.details_back);
        }

        //折叠式标题栏主题名称
        collapsingToolbarLayout.setTitle(exploretheme);
        //加载图片进details_imageView
        Glide.with(this)
                .load(imagesurl)
                .placeholder(R.drawable.explore_placeholder)
                .error(R.drawable.explore_error)
                .dontAnimate()
                .into(details_imageView);
        //加载主要内容进行TextView
        details_textView.setText(story);

        //通过explore_userid读取该条分享信息的用户信息
        Explore_details_Okhttp3();

        //添加评论，输入框
        details_edit = (EditText)findViewById(R.id.details_edit);
        //提交按钮
        details_images = (ImageView)findViewById(R.id.details_comment);
        details_images.setOnClickListener(this);

        //获取登录用户的信息
        //访问存储在本地的文件，通过键值对的方式读取想要的信息出来
        SharedPreferences preferences =getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
        user_id = preferences.getString("user_id","");
        user_name = preferences.getString("user_name","");
        user_picture = preferences.getString("user_picture","");

        //实例化recyclerView控件
        recyclerView = (RecyclerView) findViewById(R.id.comment_recyclerView);
        imageView = (ImageView) findViewById(R.id.comment_add);
        Explore_comment_Okhttp3();

    }

    /*-------------------------------------details界面信息-----------------------------------------*/
    private void Explore_details_Okhttp3(){
        //链接的地址
        String address = RequestUrl.getUrl()+"user";
        //创建RequesstBody请求体,用于数据的提交
        RequestBody requestBody=new FormBody.Builder()
                .add("id","003")
                .add("userid",explore_userid)
                .build();
        HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    Message message = new Message();
                    message.what = 2;
                    handler.sendMessage(message);
                    //取消请求
                    call.cancel();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String responseData=response.body().string();
                //分析返回的数据
                ParesJsonWithGSON(responseData);
                //更新UI
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }

    //采用GSON分析方式进行数据的转换
    private void ParesJsonWithGSON(String jsonData){

        if(jsonData!=null) {

            Gson gson = new Gson();
            //转换json数组
            //最新请求的数据
            user = gson.fromJson(jsonData, new TypeToken<User>() {
            }.getType());

        }
    }

    //返回按钮点击事件，返回上一个活动
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
           case android.R.id.home:
               finish();
               return true;
       }
       return super.onOptionsItemSelected(item);
    }

    /*-------------------------------------------添加评论------------------------------------------*/
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.details_comment:
                getedit = details_edit.getText().toString().trim();
                if(getedit!=null&&!getedit.isEmpty()) {
                    Details_Addcomment_Okhttp3();
                }else {
                    Toast.makeText(ExploreDetailsActivity.this,"评论信息不能为空",Toast
                            .LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void Details_Addcomment_Okhttp3(){
        //链接的地址
        String address = RequestUrl.getUrl()+"explore";
        //创建RequesstBody请求体,用于数据的提交
        RequestBody requestBody=new FormBody.Builder()
                .add("id","002")
                .add("user_id",user_id)
                .add("explore_id",exploreid)
                .add("user_name",user_name)
                .add("user_picture",user_picture)
                .add("comment",getedit)
                .build();
        HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    Message message = new Message();
                    message.what = 2;
                    handler.sendMessage(message);
                    //取消请求
                    call.cancel();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String responseData_add=response.body().string();
                //分析返回的数据
                ParesJsonWithGSON_Addcomment(responseData_add);
            }
        });
    }

    //采用GSON分析方式进行数据的转换
    private void ParesJsonWithGSON_Addcomment(String jsonData){

        if(jsonData!=null) {

            Gson gson = new Gson();
            Map<String,String> map = gson.fromJson(jsonData,new TypeToken<Map<String,String>>()
            {}.getType());

            backjson = map.get("back_info");

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if ("添加成功".equals(backjson)){
                        details_edit.setText("");
                        Toast.makeText(ExploreDetailsActivity.this,"添加成功",
                                Toast.LENGTH_SHORT)
                                .show();
                        //添加数据
                        comment_Add();
                        commentAdapter.addcomment(addcomment);
                        commentAdapter.notifyDataSetChanged();

                        //添加成功替换图片
                        imageView.setImageResource(R.drawable.comment_02);
                        //图片位置距离顶部300
                        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)
                                imageView.getLayoutParams();
                        lp.topMargin = 0;
                        imageView.setLayoutParams(lp);

                        //添加成功隐藏软件盘
                        InputMethodManager inputMethodManager = (InputMethodManager)
                                getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputMethodManager.hideSoftInputFromWindow(details_edit.getWindowToken(),
                                0);

                    }else {
                        Toast.makeText(ExploreDetailsActivity.this,"添加失败,请稍后再试",
                                Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });

        }
    }

    //用于添加评论成功后，及时的显示新添加的内容
    private void comment_Add(){
        addcomment = new Explore_comment();
        //获取当前日期，转换成字符串
        SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd");
        Date Date = new Date();
        String date = format.format(Date);

        addcomment.setExploreid(user_id);
        addcomment.setExploreid(exploreid);
        addcomment.setUsername(user_name);
        addcomment.setComment(getedit);
        addcomment.setDate(date);
        addcomment.setUserpicture(user_picture);
    }

    /*-------------------------------------------显示评论------------------------------------------*/
    private void Explore_comment_Okhttp3() {
        //链接的地址
        String address = RequestUrl.getUrl()+"explore";
        //创建RequesstBody请求体,用于数据的提交
        RequestBody requestBody=new FormBody.Builder()
                .add("id","003")
                .add("explore_id",exploreid)
                .build();
        HttpUtilImpl.sendOKHttpRequest(address, requestBody, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    Message message = new Message();
                    message.what = 2;
                    handler.sendMessage(message);
                    //取消请求
                    call.cancel();
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String responseData_com=response.body().string();
                //分析返回的数据
                ParesJsonWithGSON_comment(responseData_com);
            }
        });
    }

    private String  m ="";
    //采用GSON分析方式进行数据的转换
    private void ParesJsonWithGSON_comment(String jsonData){

        if(jsonData!=null) {

            Gson gson = new Gson();

            explore_comment = gson.fromJson(jsonData, new TypeToken<List<Explore_comment>>() {
            }.getType());

            for (Explore_comment i : explore_comment) {
                m = i.getUserid();
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if("-1".equals(m)) {
                        //没有评论清空
                        explore_comment.clear();
                    }
                    commentAdapter = new CommentAdapter(explore_comment);
                    //GridLayoutManager布局方式，参数1:Context，参数2:列数
                    GridLayoutManager layoutManager = new GridLayoutManager(ExploreDetailsActivity.this, 1);
                    //加载布局方式
                    recyclerView.setLayoutManager(layoutManager);
                    //recyclerView布局加载适配器
                    recyclerView.setAdapter(commentAdapter);

                    if("-1".equals(m)){
                        //该分享信息还没有评论加载的图片
                        imageView.setImageResource(R.drawable.comment_01);
                        //图片位置距离顶部300
                        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) imageView.getLayoutParams();
                        lp.topMargin = 300;
                        imageView.setLayoutParams(lp);
                    }else {
                        //有评论加载的图片
                        imageView.setImageResource(R.drawable.comment_02);
                    }
                }
            });

        }
    }

    /*-------------------------------------------更新UI-------------------------------------------*/
    public Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    details_username.setText("来自----"+user.getUsername());
                    break;
                case 2:
                    //请求服务器数据失败
                    Toast.makeText(ExploreDetailsActivity.this,"网络出错，请等待！",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

}